import Router from 'koa-router'
import model from '../model'
import ApiError from '../ApiError'
import ApiErrorNames from '../ApiError/ApiErrorNames'
const router = Router({
    prefix: '/contact_us'
})
let ContactUs = model.ContactUs
model.sync()

router.post('/', async ({request, response, body}, next) => {
    let data = request.body;
    /*
     * 可能的错误:
     *     用户邮箱重复
     */
    let result = await ContactUs.create(data)
        .catch(error => {
            throw error;
        });
    response.body = result
})

router.get('/', async ({response}, next) => {
    let results = await ContactUs.findAll()
        .catch(error => {
            throw error
        });
    response.body = results;
})

router.get('/:uuid', async ({params, response}, next) => {
    let uuid = params.uuid
    let result = await ContactUs.findById(uuid);
    if (!result) {
        throw new ApiError(ApiErrorNames.CONTACT_US_NOT_EXIST);
    }
    response.body = result
})

router.put('/:uuid', async ({params, request, response}, next) => {
    let uuid = params.uuid
    let data = request.body
    let result = await ContactUs.findById(uuid)
    if (!result) {
        throw new ApiError(ApiErrorNames.CONTACT_US_NOT_EXIST)
    }
    Object.keys(data).forEach(key => {
        result[key] = data[key]
    })
    await result.save().catch(error => {
        throw error
    })
    response.body = result
})

router.delete('/:uuid', async (ctx, next) => {
    let uuid = params.uuid
    let result = await ContactUs.findById(uuid)
    if (!result) {
        throw new ApiError(ApiErrorNames.USER_NOT_EXIST)
    }
    await result.destroy().catch(error => {
        throw error
    })
})

export default router
